package com.xhu.collegestudentrentalsystem.module.user.controller;

import com.xhu.collegestudentrentalsystem.annocation.LoginRequired;
import com.xhu.collegestudentrentalsystem.module.user.entity.House;
import com.xhu.collegestudentrentalsystem.module.user.entity.HouseOrder;
import com.xhu.collegestudentrentalsystem.module.user.entity.Page;
import com.xhu.collegestudentrentalsystem.module.user.entity.User;
import com.xhu.collegestudentrentalsystem.module.user.service.impl.HouseServiceImpl;
import com.xhu.collegestudentrentalsystem.module.user.service.impl.OrderServiceImpl;
import com.xhu.collegestudentrentalsystem.module.user.service.impl.UserServiceImpl;
import com.xhu.collegestudentrentalsystem.util.HostHolder;
import com.xhu.collegestudentrentalsystem.util.ResultData;
import com.xhu.collegestudentrentalsystem.util.constant.EnumProperty;
import com.xhu.collegestudentrentalsystem.util.constant.KeyMsg;
import com.xhu.collegestudentrentalsystem.util.constant.PointMsg;
import com.xhu.collegestudentrentalsystem.util.constant.StatusMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zhu huilin
 * @date 2023/3/13 15:13
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private OrderServiceImpl orderService;

    @Autowired
    private HouseServiceImpl houseService;

    @Autowired
    private UserServiceImpl userService;

    /**
     * 创建合同
     */
    @RequestMapping("/createOrder")
    @ResponseBody
    public ResultData createOrder(String startDate, String endDate, Long houseId) throws ParseException {
        // 没有登录时
        User user = hostHolder.getUser();
        if(user == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        if("".equals(startDate) || startDate == null){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.EMPTY_START_DATE);
        }
        if("".equals(endDate) || endDate == null){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.EMPTY_END_DATE);
        }

        // 检查日期
        SimpleDateFormat format = new SimpleDateFormat(EnumProperty.DATA_TRANSFORM);
        Date startDate1 = format.parse(startDate);
        Date endDate1 = format.parse(endDate);
        if(endDate1.before(startDate1) || startDate1.before(new Date(new Date().getTime() - 24*60*60*1000))){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.ERROR_DATE_RANGE);
        }

        // 查询 并填充数据 ，生成订单数据
        Boolean isCreated = orderService.isCreatedOrder(startDate1, endDate1, houseId, user.getId());
        if(isCreated){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.REPEAT_ORDER_DATE);
        }
        HouseOrder order = orderService.createOrder(startDate1, endDate1, houseId, user.getId());
        if(order == null){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.ORDER_FAIL);
        }
        // 生成订单成功后，将订单id作为data传回到前端
        ResultData resultData = new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.ORDER_SUCCESS);
        resultData.put(KeyMsg.order.ORDER_ID, order.getId());
        return resultData;
    }

    /**
     * 查看合同信息
     */
    @LoginRequired
    @RequestMapping("/orderInfo")
    public String orderInfo(@RequestParam("orderId") Long orderId, Model model){
        // 查询订单信息
        HouseOrder order = orderService.findHouseOrderById(orderId);
        if(order == null){
            return "error/404";
        }
        // 查询房屋信息
        House house = houseService.findHouseById(order.getHouseId());
        order.setHouse(house);

        // 查询房东信息
        User owner = userService.findUserById(order.getOwnerUserId());
        order.setOwnerUser(owner);

        // 查询顾客信息
        User customer = userService.findUserById(order.getCustomerUserId());
        order.setCustomerUser(customer);

        model.addAttribute(KeyMsg.order.ORDER, order);

        return "site/agreement";
    }

    /**
     * 签订合同后，修改订单状态
     */
    @RequestMapping("/agreementOrder")
    @ResponseBody
    public ResultData agreementOrder(Long orderId){
        User user = hostHolder.getUser();
        if(user == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        // 查询订单信息
        HouseOrder order = orderService.findHouseOrderById(orderId);
        if(order == null){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.UN_EXIST_ORDER);
        }
        // 查询房子信息是否正确且可以租
        House house = houseService.findHouseById(order.getHouseId());
        if(house == null || house.getStatus() != StatusMsg.houseStatus.UN_RENT){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.NO_PERMISSION_SIGN);
        }

        // 查询房东信息
        User owner = userService.findUserById(order.getOwnerUserId());
        if(owner == null){
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.UN_EXIST_HOUSE_OWNER);
        }

        // 修改房屋状态为待支付
        Integer result = orderService.updateOrderStatusToWaitPay(orderId, StatusMsg.orderStatus.WAIT_PAY);
        if(result > 0){
            ResultData resultData = new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.SIGN_SUCCESS);
            resultData.put(KeyMsg.order.ORDER_ID, orderId);
            return resultData;
        }
        return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.SIGN_FAIL);
    }

    /**
     * 支付页面
     */
    @LoginRequired
    @RequestMapping("/payInfo")
    public String payInfo(Long orderId, Model model){
        // 查询订单信息
        HouseOrder order = orderService.findHouseOrderById(orderId);
        if(order == null){
            model.addAttribute(KeyMsg.MSG, PointMsg.order.UN_EXIST_ORDER);
            return "error/404";
        }
        // 查询房屋信息
        House house = houseService.findHouseById(order.getHouseId());
        order.setHouse(house);

        // 查询房东信息
        User owner = userService.findUserById(order.getOwnerUserId());
        order.setOwnerUser(owner);

        // 查询顾客信息
        User customer = userService.findUserById(order.getCustomerUserId());
        order.setCustomerUser(customer);

        // 登录用户不是该订单的租客、房东或管理员，就不能查看合同
        if(hostHolder.getUser().getId() != order.getCustomerUserId() && hostHolder.getUser().getId() != order.getOwnerUserId() && !"admin".equals(hostHolder.getUser().getRole())){
            model.addAttribute(KeyMsg.MSG, PointMsg.order.NO_PERMISSION_CHECK);
            return "/index";
        }

        model.addAttribute(KeyMsg.order.ORDER, order);
        return "site/pay";
    }

    /**
     * 模拟支付成功，支付成功：
     *      1. 将订单状态修改为0生效中
     *      2. 设置定时任务，订单到期将状态修改为1已到期
     */
    @RequestMapping("/payOrder")
    @ResponseBody
    public ResultData payOrder(Long orderId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        Integer result = orderService.orderPayed(orderId);
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.PAY_SUCCESS);
        }else {
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.PAY_FAIL);
        }
    }

    /**
     * 查询订单信息：
     *      如果登录的是顾客用户，则查询该用户的所有订单信息
     *      如果登录的是房东用户，则查询房东已出租的房屋订单信息
     *      如果是管理员，则查询所有的订单信息
     */
    @LoginRequired
    @RequestMapping("/orderList")
    public String orderList(Page page, Model model){
        // 分页信息
        page.setLimit(3);
        // 登录用户信息
        User user = hostHolder.getUser();
        List<HouseOrder> orders = orderService.findOrdersByUser(user, page);
        page.setPath("/order/orderList");
        model.addAttribute(KeyMsg.order.ORDER_LIST, orders);
        return "site/order-list";
    }

    /**
     * 用户取消订单
     */
    @RequestMapping("/cancelOrder")
    @ResponseBody
    public ResultData cancelOrder(Long orderId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        // 修改订单状态 为 用户已取消
        Integer result = orderService.updateOrderStatus(orderId, StatusMsg.orderStatus.CUSTOMER_CANCEL);
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.CANCEL_ORDER_SUCCESS);
        }else {
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.CANCEL_ORDER_FAIL);
        }
    }

    /**
     * 用户申请退租
     */
    @RequestMapping("/applyDrawbackOrder")
    @ResponseBody
    public ResultData applyDrawbackOrder(Long orderId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        // 修改订单状态 为 用户省去退租
        Integer result = orderService.updateOrderStatus(orderId, StatusMsg.orderStatus.APPLY_DRAWBACK);
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.ASK_RETURN_SUCCESS);
        }else {
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.ASK_RETURN_FAIL);
        }
    }

    /**
     * 房东同意退租申请
     */
    @RequestMapping("/drawback")
    @ResponseBody
    public ResultData drawback(Long orderId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        // 修改订单状态 为 已退租
        Integer result = orderService.updateOrderStatus(orderId, StatusMsg.orderStatus.HAS_DRAWBACK);
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.RETURN_ORDER_SUCCESS);
        }else {
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.RETURN_ORDER_FAIL);
        }
    }

    /**
     * 房东不同意用户退租
     */
    @RequestMapping("/drawbackFail")
    @ResponseBody
    public ResultData drawbackFail(Long orderId){
        if(hostHolder.getUser() == null){
            return new ResultData(ResultData.LOGIN_FAIL, PointMsg.login.UN_LOGIN);
        }
        // 修改订单状态 为 已退租
        Integer result = orderService.updateOrderStatus(orderId, StatusMsg.orderStatus.DRAWBACK_FAIL);
        if(result > 0){
            return new ResultData(ResultData.OPERATION_SUCCESS, PointMsg.order.BACK_ASK_SUCCESS);
        }else {
            return new ResultData(ResultData.OPERATION_FAIL, PointMsg.order.BACK_ASK_FAIL);
        }
    }


}
